package main

import (
	"chi-med-det-server-go/database"
	"chi-med-det-server-go/middlewares"
	"chi-med-det-server-go/models"
	"fmt"
	"net/http"
	"regexp"
	"strings"

	"github.com/gin-gonic/gin"

	_ "chi-med-det-server-go/docs"

	swaggerfiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

const (
	LOGIN_SUCCESS      = "登录成功"
	ILLEGAL_LOGININFO  = "用户名或密码不正确, 请重试"
	SIGNUP_SUCCESS     = "注册成功"
	ILLEGAL_SIGNUPINFO = "用户名或密码非法, 请重试"
	FEEDBACK_SUCCESS   = "反馈成功"
	ILLEGAL_FEEDBACK   = "反馈信息非法"
)

func makeQuestionList() []models.Question {
	questionList := []models.Question{
		{
			NO:          1,
			Title:       "您的皮肤或者唇干吗？",
			Options:     []string{"没有", "很少", "有时", "经常", "总是"},
			SelectIndex: -1,
		},
		{
			NO:          2,
			Title:       "您口唇的颜色比一般人红吗？",
			Options:     []string{"没有", "很少", "有时", "经常", "总是"},
			SelectIndex: -1,
		},
		{
			NO:          3,
			Title:       "您面部两颧潮红或偏红吗？",
			Options:     []string{"没有", "很少", "有时", "经常", "总是"},
			SelectIndex: -1,
		},
		{
			NO:          4,
			Title:       "您感到胸闷或腹部胀满吗？",
			Options:     []string{"没有", "很少", "有时", "经常", "总是"},
			SelectIndex: -1,
		},
		{
			NO:          5,
			Title:       "您感到身体沉重不轻松或不攀爽快吗？",
			Options:     []string{"没有", "很少", "有时", "经常", "总是"},
			SelectIndex: -1,
		},
	}
	return questionList
}

func makeDetResult(ctx *gin.Context) models.DetResult {
	var answers models.Answers
	score := 0
	detResult := models.DetResult{}
	if err := ctx.ShouldBind(&answers); err == nil {
		for _, answer := range answers.AnswerList {
			fmt.Printf("/getDetResult, answer=%v\n", answer)
			score += answer.Index
		}
		if score < 4 {
			detResult.Diagnosis = "无异常"
			detResult.Suggestion = []string{"请继续保持优秀的生活习惯"}
		} else if score < 8 {
			detResult.Diagnosis = "无明显异常，身体状态良好"
			detResult.Suggestion = []string{"保持均衡饮食，多喝水，避免过度清洁皮肤",
				"注意防晒，使用温和保湿产品",
				"适度运动，保持心情舒畅"}
		} else if score < 12 {
			detResult.Diagnosis = "可能存在阴虚或湿热倾向，如口干、轻微腹胀"
			detResult.Suggestion = []string{"少吃辛辣、油炸食物，多吃滋阴祛湿食物（如银耳、百合、冬瓜、薏米）",
				"避免熬夜，保持规律作息；适当出汗（如快走、瑜伽）",
				"选择无酒精护肤品，定期敷保湿面膜"}
		} else if score < 16 {
			detResult.Diagnosis = "阴虚火旺或湿热内蕴，如面部潮红、身体沉重"
			detResult.Suggestion = []string{"咨询中医师，可考虑知柏地黄丸（阴虚）或三仁汤（湿热）",
				"增加梨、甘蔗、赤小豆等食物；避免烟酒",
				"尝试拔罐、艾灸祛湿，或按摩太冲穴（疏肝理气）",
				"若症状持续加重，建议检查甲状腺功能或激素水平"}
		} else if score >= 16 {
			detResult.Diagnosis = "严重阴虚或湿热，需警惕疾病（如更年期综合征、代谢异常）"
			detResult.Suggestion = []string{"排查糖尿病、红斑狼疮等疾病，必要时中西医结合治疗）",
				"禁食辛辣、海鲜、温补食物（如羊肉、桂圆）",
				"避免高温环境，穿透气衣物；保持情绪稳定",
				"在医生指导下使用清热凉血方剂（如犀角地黄汤）"}
		}
	} else {
		fmt.Printf("makeDetResult(), err=%v\n", err)
	}
	return detResult
}

var dbUtil database.DBUtil

func init() {
	dbUtil = database.DBUtil{}
	dbUtil.InitDataBase()
}

// @Tags  登录/注册
// @Summary 用户登录
// @Accept application/json
// @Produce application/json
// @Param loginInfo body models.LoginInfo true "已注册的用户名与密码。若是新用户，则需要先进行注册"
// @Router /login [post]
func login(ctx *gin.Context) {
	var loginInfo models.LoginInfo
	if err := ctx.ShouldBind(&loginInfo); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"msg":  ILLEGAL_LOGININFO,
			"code": -1,
		})
	} else {
		fmt.Printf("/login, account=%s, password=%s\n", loginInfo.Account, loginInfo.Password)
		user := dbUtil.QueryUserByAccount(strings.TrimSpace(loginInfo.Account))
		if user != nil && strings.TrimSpace(loginInfo.Password) == user.Password {
			ctx.JSON(http.StatusOK, gin.H{
				"msg":  LOGIN_SUCCESS,
				"code": 0,
			})
		} else {
			ctx.JSON(http.StatusBadRequest, gin.H{
				"msg":  ILLEGAL_LOGININFO,
				"code": -1,
			})
		}
	}
}

// @Tags  登录/注册
// @Summary 用户注册
// @Accept application/json
// @Produce application/json
// @Param signupInfo body models.SignupInfo true "用户名与密码。用户名由字母与数字组成，且必须以字母开头，长度6-12; 密码由字母与数字组成，长度6-12位。"
// @Router /signup [post]
func signup(ctx *gin.Context) {
	var signupInfo models.SignupInfo
	if err := ctx.ShouldBind(&signupInfo); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"msg":  ILLEGAL_SIGNUPINFO,
			"code": -1,
		})
	} else {
		fmt.Printf("/signup, account=%s, password=%s, confirmPass=%s\n", signupInfo.Account, signupInfo.Password, signupInfo.ConfirmPass)
		accountReg := regexp.MustCompile(`^[a-zA-Z]\w{5,11}`)
		passwordReg := regexp.MustCompile(`^[A-Za-z\d]{6,12}$`)
		if accountReg.Match([]byte(signupInfo.Account)) && passwordReg.Match([]byte(signupInfo.Password)) && signupInfo.Password == signupInfo.ConfirmPass {
			ret := dbUtil.InsertUser(
				models.User{
					Account:  signupInfo.Account,
					Password: signupInfo.Password,
				},
			)
			if ret {
				ctx.JSON(http.StatusOK, gin.H{
					"msg":  SIGNUP_SUCCESS,
					"code": 0,
				})
			} else {
				ctx.JSON(http.StatusBadRequest, gin.H{
					"msg":  ILLEGAL_SIGNUPINFO,
					"code": -1,
				})
			}
		} else {
			ctx.JSON(http.StatusBadRequest, gin.H{
				"msg":  ILLEGAL_SIGNUPINFO,
				"code": -1,
			})
		}
	}
}

// @Tags  用户反馈
// @Summary 用户反馈
// @Accept application/json
// @Produce application/json
// @Param feedback body models.Feedback true "用户反馈，内容长弃不超过30"
// @Router /feedback [post]
func feedback(ctx *gin.Context) {
	var feedback models.Feedback
	if err := ctx.ShouldBind(&feedback); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"msg":  ILLEGAL_FEEDBACK,
			"code": -1,
		})
	} else {
		dbUtil.InsertFeedback(feedback)
		ctx.JSON(http.StatusOK, gin.H{
			"msg":  FEEDBACK_SUCCESS,
			"code": 0,
		})
	}
}

// @title 中医体质检测系统
// @version 1.0
// @description 通过问卷调查的方式，对被调查者进行体质诊断与诊疗建议服务
// @host 127.0.0.1:8000
// @BasePath /
func main() {

	r := gin.Default()

	r.Use(middlewares.Cors())
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))

	// Login
	r.POST("/login", login)

	// Signup
	r.POST("/signup", signup)
	// GetQuestionList
	r.GET("/getQuestionList", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{
			"questionList": makeQuestionList(),
		})
	})
	// GetDetResult
	r.POST("/getDetResult", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{
			"detResult": makeDetResult(ctx),
		})
	})
	// Feedback
	r.POST("/feedback", feedback)

	r.Run(":8000")
}
